package interview.meituan;

/**
 * @author why
 * @data 2021/9/8
 * 第k大的数 快排版
 */
public class K {
    static int retNumber = 0;

    public static void main(String[] args) {
        int arr[] = {2, 4, 1, 8, 6, 7, 9, 3, 5};
        int k = 9;
        if (k > arr.length) {
            return;
        }
        quickSort(arr, 0, arr.length - 1, k);
        System.out.println(arr[retNumber]);
    }

    public static void quickSort(int[] arr, int l, int r, int k) {
        int[] p = partition(arr, l, r);
        retNumber = p[1];
        if (l < r) {
            if (k > p[1]) {
                quickSort(arr, p[1] + 1, r, k);
            } else if (k <= p[0]) {
                quickSort(arr, l, p[0] - 1, k);
            }
        }
    }

    public static int[] partition(int[] arr, int l, int r) {
        int less = l - 1;
        int more = r;
        while (l < more) {
            if (arr[l] < arr[r]) {
                swap(arr, ++less, l++);
            } else if (arr[l] > arr[r]) {
                swap(arr, --more, l);
            } else {
                l++;
            }
        }
        swap(arr, more, r);
        return new int[]{less + 1, more};
    }

    public static void swap(int[] arr, int i, int j) {
        int tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }
}
